﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UCS.XNA.Utils.Animation
{
    public class OffsetTranslateAnimation
    {
        #region Attributes and Properties

        private float _speed;
        public float Speed
        {
            get { return _speed; }
        }

        private Vector2 _direction;
        public Vector2 Direction
        {
            get { return _direction; }
        }

        private float _distance;
        public float Distance
        {
            get { return _distance; }
        }

        private bool _isFinished;
        public bool IsFinished
        {
            get { return _isFinished; }
        }

        #endregion

        #region Private Members

        private float _traveled = 0f;
        private ITranslateAnimatable _target;

        #endregion

        #region Events

        public virtual event EventHandler<EventArgs> AnimationFinished;

        #endregion

        #region Constructors

        public OffsetTranslateAnimation(ITranslateAnimatable target, Vector2 direction, float distance, float speed)
        {
            _target = target;
            _direction = direction;
            _distance = distance;
            _speed = speed;
            _isFinished = false;
        }

        #endregion

        #region Public Methods

        public void Update(GameTime gameTime)
        {
            if (_traveled < _distance && !this._isFinished)
            {
                Vector2 normal = _direction;
                float speed = System.Math.Min(_speed, _distance - _traveled);
                normal.Normalize();
                normal *= speed;
                _traveled += speed;

                _target.Position += normal;
            }
            else if (!this._isFinished)
            {
                this._isFinished = true;
                this.RaiseAnimationFinishedEvent();
            }
        }

        #endregion

        #region Protected Methods

        public void RaiseAnimationFinishedEvent()
        {
            if (this.AnimationFinished != null)
                this.AnimationFinished(this, new EventArgs());
        }

        #endregion
    }
}
